<?php
/**
 * http响应Traits
 * Date: 2025/08/31
 */

namespace App\Http\Traits;

use Illuminate\Http\JsonResponse;

trait ApiResponse
{
    /**
     * @var int 当前httpCode
     */
    protected $httpCode = 200;

    /**
     * 成功返回
     * @date 2024/06/12
     * @param array $data 成功数据
     * @param int $code 成功code
     * @param string $message 成功信息
     * @return JsonResponse
     */
    public function success($data = [], $message = 'success',  $code = 200)
    {
        return $this->send(compact('data'), $message, $code);
    }

    /**
     * 失败返回
     * @date 2024/06/12
     * @param string $message 失败信息
     * @param int $code 失败code
     * @return JsonResponse
     */
    public function failed($message = 'error', $code = 400)
    {
        return $this->send([], $message, $code);
    }

    /**
     * http响应
     * @param array $data 返回数据
     * @param int $code 返回code
     * @param string $message 返回信息
     * @return JsonResponse
     */
    public function send($data, $message, $code)
    {
        // header头定义
        $header = ['Request_Id' => REQUEST_ID];

        // 返回值处理
        $data = array_merge([
            'code' => $code,
            'message' => $message,
        ], $data);
        return response()->json($data, $this->httpCode, $header, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 设置当前httpCode
     * @param int $httpCode 返回的httpCode
     * @return $this
     */
    public function setHttpCode($httpCode)
    {
        $this->httpCode = $httpCode;
        return $this;
    }
}
